<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="PragmaticScala">
<meta name="generator" content="Paradox, paradox-material-theme=0.5.1, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="PragmaticScala">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>第7章——特质 · </title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
</span>
<span class="md-header-nav__topic">
第7章——特质
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="">
</a>
</label>
<ul>
  <li><a href="../contents.html" class="page">目录</a>
  <ul>
    <li><a href="../abstract.html" class="page">内容提要</a></li>
    <li><a href="../part1.html" class="page">第一部分 小试牛刀</a></li>
    <li><a href="../part2.html" class="page">第二部分 深入 Scala</a></li>
    <li><a href="../part3.html" class="page">第三部分 Scala 中的并发编程</a></li>
    <li><a href="../part4.html" class="page">第四部分 Scala 实战</a></li>
    <li><a href="../refs/references.html" class="page">参考书目</a></li>
    <li><a href="../extras.html" class="page">额外指引</a></li>
    <li><a href="../errata.html" class="page">勘误</a></li>
  </ul></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-07/index.html#第7章-特质" class="header">第7章——特质</a>
  <ul>
    <li><a href="../chapter-07/index.html#7-1-理解特质" class="header">7.1 理解特质</a></li>
    <li><a href="../chapter-07/index.html#7-2-选择性混入" class="header">7.2 选择性混入</a></li>
    <li><a href="../chapter-07/index.html#7-3-使用特质实现装饰器模式" class="header">7.3 使用特质实现装饰器模式</a></li>
    <li><a href="../chapter-07/index.html#7-4-特质中的方法延迟绑定" class="header">7.4 特质中的方法延迟绑定</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../chapter-07/index.html#第7章-特质" class="header">第7章——特质</a>
  <ul>
    <li><a href="../chapter-07/index.html#7-1-理解特质" class="header">7.1 理解特质</a></li>
    <li><a href="../chapter-07/index.html#7-2-选择性混入" class="header">7.2 选择性混入</a></li>
    <li><a href="../chapter-07/index.html#7-3-使用特质实现装饰器模式" class="header">7.3 使用特质实现装饰器模式</a></li>
    <li><a href="../chapter-07/index.html#7-4-特质中的方法延迟绑定" class="header">7.4 特质中的方法延迟绑定</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#第7章-特质" name="第7章-特质" class="anchor"><span class="anchor-link"></span></a>第7章——特质</h1>
<p>Java 只允许单继承，这会强制建立一种线性的层次结构模型。但现实世界中充满了横切 关注点（crosscutting concerns）—一种横切且影响多个抽象的概念，这些抽象并不同属于 某个单一的类层次结构 ① 。在典型的企业级应用程序中，安全、日志记录、验证、事务以及 资源管理都是这些横切关注点的应用场景。但是，因为我们受限于单一的类层次结构，所以 实现这些横切关注点变得相当困难，往往需要代码上的重复或者引入重量级工具 ② 。Scala 使 用特质（trait）解决了这个问题。</p>
<blockquote>
  <ol>
    <li>即横跨应用程序中多个模块的特性。——译者注</li>
  </ol>
</blockquote>
<h2><a href="#7-1-理解特质" name="7-1-理解特质" class="anchor"><span class="anchor-link"></span></a>7.1 理解特质</h2>
<blockquote>
  <p>UsingTraits/HumanWithListen.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Human(val name: String) {
  def listen(): Unit = println(s&quot;Your friend $name is listening&quot;)
}

class Man(override val name: String) extends Human(name)
class Woman(override val name: String) extends Human(name)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/HumanWithListen.scala#L21-L26">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Friend.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">trait Friend {
  val name: String
  def listen(): Unit = println(s&quot;Your friend $name is listening&quot;)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Friend.scala#L20-L23">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Human.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Human(val name: String) extends Friend

class Woman(override val name: String) extends Human(name)
class Man(override val name: String) extends Human(name)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Human.scala#L20-L23">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Dog.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Dog(val name: String) extends Animal with Friend {
  //optionally override method here.
  override def listen(): Unit = println(s&quot;$name&#39;s listening quietly&quot;)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Dog.scala#L20-L23">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Animal.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Animal</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Animal.scala#L20">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/UseFriend.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">object UseFriend extends App {
  val john = new Man(&quot;John&quot;)
  val sara = new Woman(&quot;Sara&quot;)
  val comet = new Dog(&quot;Comet&quot;)

  john.listen()
  sara.listen()
  comet.listen()

  val mansBestFriend: Friend = comet
  mansBestFriend.listen()

  def helpAsFriend(friend: Friend): Unit = friend.listen()

  helpAsFriend(sara)
  helpAsFriend(comet)
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/UseFriend.scala#L20-L36">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Your friend John is listening
Your friend Sara is listening
Comet&#39;s listening quietly
Comet&#39;s listening quietly
Your friend Sara is listening
Comet&#39;s listening quietly</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/shoutput/RunUseFriend.output#L2-L7">Full source at GitHub</a>
<h2><a href="#7-2-选择性混入" name="7-2-选择性混入" class="anchor"><span class="anchor-link"></span></a>7.2 选择性混入</h2>
<blockquote>
  <p>UsingTraits/Cat.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class Cat(val name: String) extends Animal</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Cat.scala#L20">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/UseCat.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">object UseCat extends App {
  def useFriend(friend: Friend): Unit = friend.listen()

  val alf = new Cat(&quot;Alf&quot;)
  val friend: Friend = alf // ERROR

  useFriend(alf) // ERROR
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/test/scala/chapter7/UseCat.scala#L20-L27">Full source at GitHub</a>
<p><em>编译结果</em></p>
<pre class="prettyprint"><code class="language-output">UseCat.scala:5: error: type mismatch;
 found   : Cat
 required: Friend
  val friend : Friend = alf // ERROR
                        ^
UseCat.scala:7: error: type mismatch;
 found   : Cat
 required: Friend
  useFriend(alf) // ERROR
            ^
two errors found</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/shoutput/RunUseCat.output#L2-L12">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/TreatCatAsFriend.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">def useFriend(friend: Friend): Unit = friend.listen()

val angel = new Cat(&quot;Angel&quot;) with Friend
val friend: Friend = angel
angel.listen()

useFriend(angel)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/TreatCatAsFriend.scala#L22-L28">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Your friend Angel is listening
Your friend Angel is listening</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/shoutput/RunTreatCatAsFriend.output#L2-L3">Full source at GitHub</a>
<h2><a href="#7-3-使用特质实现装饰器模式" name="7-3-使用特质实现装饰器模式" class="anchor"><span class="anchor-link"></span></a>7.3 使用特质实现装饰器模式</h2>
<blockquote>
  <p>UsingTraits/Decorator.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">abstract class Check {
  def check: String = &quot;Checked Application Details...&quot;
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Decorator.scala#L21-L23">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Decorator.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">trait CreditCheck extends Check {
  override def check: String = s&quot;Checked Credit... ${super.check}&quot;
}

trait EmploymentCheck extends Check {
  override def check: String = s&quot;Checked Employment...${super.check}&quot;
}

trait CriminalRecordCheck extends Check {
  override def check: String = s&quot;Check Criminal Records...${super.check}&quot;
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Decorator.scala#L27-L37">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Decorator.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val apartmentApplication =
  new Check with CreditCheck with CriminalRecordCheck

println(apartmentApplication.check)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Decorator.scala#L41-L44">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/Decorator.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val employmentApplication =
  new Check with CriminalRecordCheck with EmploymentCheck

println(employmentApplication.check)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/Decorator.scala#L48-L51">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">Check Criminal Records...Checked Credit... Checked Application Details...
Checked Employment...Check Criminal Records...Checked Application 
Details...</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/output/Decorator.output#L2-L4">Full source at GitHub</a>
<h2><a href="#7-4-特质中的方法延迟绑定" name="7-4-特质中的方法延迟绑定" class="anchor"><span class="anchor-link"></span></a>7.4 特质中的方法延迟绑定</h2>
<blockquote>
  <p>UsingTraits/MethodBinding.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">abstract class Writer {
  def writeMessage(message: String): Unit
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/MethodBinding.scala#L21-L23">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/MethodBinding.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">trait UpperCaseWriter extends Writer {
  abstract override def writeMessage(message: String): Unit =
    super.writeMessage(message.toUpperCase)
}

trait ProfanityFilteredWriter extends Writer {
  abstract override def writeMessage(message: String): Unit =
    super.writeMessage(message.replace(&quot;stupid&quot;, &quot;s-----&quot;))
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/MethodBinding.scala#L27-L35">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/MethodBinding.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">class StringWriterDelegate extends Writer {
  val writer = new java.io.StringWriter

  def writeMessage(message: String): Unit = writer.write(message)
  override def toString: String = writer.toString
}</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/MethodBinding.scala#L39-L44">Full source at GitHub</a>
<blockquote>
  <p>UsingTraits/MethodBinding.scala</p>
</blockquote>
<pre class="prettyprint"><code class="language-scala">val myWriterProfanityFirst =
  new StringWriterDelegate with UpperCaseWriter with ProfanityFilteredWriter

val myWriterProfanityLast =
  new StringWriterDelegate with ProfanityFilteredWriter with UpperCaseWriter

myWriterProfanityFirst writeMessage &quot;There is no sin except stupidity&quot;
myWriterProfanityLast writeMessage &quot;There is no sin except stupidity&quot;

println(myWriterProfanityFirst)
println(myWriterProfanityLast)</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/MethodBinding.scala#L48-L58">Full source at GitHub</a>
<p><em>运行结果</em></p>
<pre class="prettyprint"><code class="language-output">THERE IS NO SIN EXCEPT S-----ITY
THERE IS NO SIN EXCEPT STUPIDITY</code></pre><a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/v1.0.0/src/main/scala/chapter7/output/MethodBinding.output#L2-L3">Full source at GitHub</a>
</div>
<div>
<a href="https://github.com/ReactivePlatform/Pragmatic-Scala.git/tree/master/src/paradox/chapter-07/index.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../chapter-06/index.html" title="第6章——函数值和闭包" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
第6章——函数值和闭包
</span>
</div>
</a>
<a href="../chapter-08/index.html" title="第8章——集合" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
第8章——集合
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
